<?php
/**
 * 用户模型
 */

namespace app\common\model;

use think\model\concern\SoftDelete;
use app\common\server\UrlServer;
use think\db;
class User extends Model
{
    use SoftDelete;
    public $softDelete = true;
    protected $name = 'user';
    protected $autoWriteTimestamp = true;

    //可搜索字段
    protected $searchField = ['username', 'mobile', 'nickname',];

    //头像
    public function getAvatarAttr($value, $data)
    {
        if ($value) {
            return UrlServer::getFileUrl($value);
        }
        return $value;
    }

    //是否启用用户体验收益资格
    public function getExperienceTextAttr($value, $data)
    {
        return self::EXPERIENCE_TEXT[$data['is_experience']];
    }
    //是否启用获取器
    public function getStatusTextAttr($value, $data)
    {
        return self::BOOLEAN_TEXT[$data['status']];
    }

    //用户等级
    public function getUserLevelIdTextAttr($value, $data)
    {
        return self::LEVL_TEXT[$data['user_level_id']];
    }

    //关联用户等级
    public function userLevel()
    {
        return $this->belongsTo(UserLevel::class);
    }

    public function getBaseAvatarAttr($value, $data)
    {
        return $data['avatar'];
    }
    public function level()
    {
        return $this->hasOne('UserLevel','id', 'level');
    }

    public static function getUserInfo($userId)
    {
        $user = self::field('id,sn,nickname,avatar,mobile')->findOrEmpty($userId)->toArray();
        if (empty($user)) {
            return '系统';
        }
        return $user;
    }

    //用户登录
    public static function login($param)
    {
        $username = $param['username'];
        $password = $param['password'];
        $user     = self::get(['username' => $username]);
        if (!$user) {
            exception('用户不存在');
        }

        if (!password_verify($password, $user->password)) {
            exception('密码错误');
        }

        if ((int)$user->status !== 1) {
            exception('用户被冻结');
        }
        return $user;
    }
}
